package net.example.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.oraycn.esbasic.helpers.StringHelper;
import com.oraycn.esframework.core.ClientType;
import com.oraycn.omcs.ICamOpenOverCallback;
import com.oraycn.omcs.MultimediaManagerFactory;
import com.oraycn.omcs.core.CameraConnector;
import com.oraycn.omcs.core.CameraSurfaceView;
import com.oraycn.omcs.core.MicrophoneConnector;
import com.oraycn.omcs.core.OMCSSurfaceView;

import net.example.manager.ClientGlobalCache;
import net.example.model.event.CallEvent;
import net.example.manager.GGApplication;
import net.example.model.event.RequestEvent;
import net.example.model.event.UserEvent;
import net.example.manager.Manager;
import net.example.model.CommunicateMediaType;
import net.example.model.CommunicateType;
import net.example.model.GGUser;
import net.example.model.UserStatus;
import net.example.ggtalk.R;
import net.example.utils.HeadImgHelper;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUtil;

import de.greenrobot.event.EventBus;

/**
 *
 */
public class VideoCallActivity extends Activity implements ICamOpenOverCallback {
    Handler mHandler = new Handler();
    Thread thread2;
    CameraSurfaceView myView = null;
    OMCSSurfaceView otherView = null;
    LinearLayout coming_callLayout = null,switch_camera_layout,ll_top_container;
    TextView tv_nick,tv_tips;
    Button hangup, pickup, refuse;
    Chronometer call_time;
    CameraConnector cameraConnector;
    MicrophoneConnector microphoneConnector;
    String userId = "";
    String loginID = "";
    ClientType clientType;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_videocall);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        MultimediaManagerFactory.GetSingleton().setCameraOpenCallBack(this);
        MultimediaManagerFactory.GetSingleton().getAudioMessageController().dispose();
        AndroidUtil.OpenSpeaker(VideoCallActivity.this);
        myView = (CameraSurfaceView) findViewById(R.id.local_surface);
        myView.setZOrderOnTop(true);
        tv_nick = (TextView) findViewById(R.id.tv_nick);
        tv_tips=(TextView)findViewById(R.id.tv_tips);
        call_time=(Chronometer)findViewById(R.id.call_time);
//        call_time.setVisibility(View.GONE);
        otherView = (OMCSSurfaceView) findViewById(R.id.opposite_surface);
//        otherView.setVideoScale(true);//设置视频框中视频显示模式  true为等比缩放；false为 拉升填充
        hangup = (Button) findViewById(R.id.btn_hangup_call);
        pickup = (Button) findViewById(R.id.btn_answer_call);
        refuse = (Button) findViewById(R.id.btn_refuse_call);
        ImageView friend_img=(ImageView)findViewById(R.id.iv_friend_img);
        ll_top_container=(LinearLayout)findViewById(R.id.ll_top_container);
        coming_callLayout = (LinearLayout) findViewById(R.id.ll_coming_call);
        switch_camera_layout=(LinearLayout)findViewById(R.id.switch_camera);
        //对方请求视频
        if (getIntent().hasExtra("event")) {
            RequestEvent event = (RequestEvent) getIntent().getSerializableExtra("event");
            if (event != null) {
                userId = event.requestID;
                loginID = event.getLoginID();
                clientType = event.clientType;
            }
        }

        GGApplication.getInstance().ringForCalling();
        if (StringHelper.isNullOrEmpty(userId)) {
            //我向对方发起视频
            userId = getIntent().getStringExtra("requestID");
            if (StringHelper.isNullOrEmpty(userId)) {
                tv_nick.setText("未知requestID");
            } else {
                coming_callLayout.setVisibility(View.GONE);
                hangup.setBackgroundResource(R.drawable.call_cancel_bg);
                hangup.setVisibility(View.VISIBLE);
                Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Video, CommunicateType.Request, "", -1);
                tv_tips.setText("正在等待对方接受邀请");
            }
        }else {
            //对方向我发起视频
            tv_tips.setText("邀请你视频通话");
            coming_callLayout.setVisibility(View.VISIBLE);
         }

        GGUser GGUser = ClientGlobalCache.getInstance().getUser(userId);
        if (GGUser != null) {
            tv_nick.setText(GGUser.getName());
            HeadImgHelper.setUserHeadImg(friend_img, GGUser);
        } else {
            tv_nick.setText("未知用户");
        }

        hangup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int destType = -1;
                    if (clientType != null) {
                        destType = clientType.ordinal();
                    }
                    Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Video, CommunicateType.Terminate, "", destType);
                    terminate("视频已中断!");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        pickup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GGApplication.getInstance().stopRingForCalling();
                GGUser destUser= ClientGlobalCache.getInstance().getUser4Cache(userId);
                if(destUser==null||destUser.getUserStatus()==UserStatus.OffLine)//对方离线了，直接提示挂断
                {
                    terminate("对方已挂断");
                    return;
                }
                int destType = -1;
                if (clientType != null) {
                    destType = clientType.ordinal();
                }
                coming_callLayout.setVisibility(View.GONE);
                openConnector();
                Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Video, CommunicateType.Agree, "", destType);
            }
        });

        refuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int destType = -1;
                if (clientType != null) {
                    destType = clientType.ordinal();
                }
                Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Video, CommunicateType.Reject, "", destType);
                GGApplication.getInstance().stopRingForCalling();
                finish();
            }
        });

        ImageView iv_switch_camera =(ImageView)findViewById(R.id.iv_switch_camera);
        iv_switch_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int index = MultimediaManagerFactory.GetSingleton().getCameraDeviceIndex();
                    int new_index = index == 0 ? 1 : 0;
                    MultimediaManagerFactory.GetSingleton().switchCameraDeviceIndex(new_index);
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        try {
            if (thread2 != null) {
                thread2.interrupt();
            }
            closeConnectors();
            EventBus.getDefault().unregister(this);
            AndroidUtil.CloseSpeaker(this,AndroidUtil.getCurrentVolume(this));
            super.onDestroy();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Video, CommunicateType.Terminate, "", clientType.ordinal());
                terminate("视频已中断!");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }


    private void agree(CallEvent event) {
        GGApplication.getInstance().stopRingForCalling();
        userId = event.target;
        loginID = event.getTagetLoginID();
        clientType = event.clientType;
        openConnector();
    }

    private void terminate(String message) {
        GGApplication.getInstance().stopRingForCalling();
        Manager.getInstance().sendSystemMessage(userId,message,false);// 发送系统消息
        finish();
        ToastUtils.showLong(GGApplication.applicationContext, message);
    }

    private void openConnector() {
        try {
            if (thread2 != null) {
                thread2.interrupt();
            }
            hangup.setVisibility(View.VISIBLE);
            hangup.setBackgroundResource(R.drawable.voice_call_hangup_bg);
            switch_camera_layout.setVisibility(View.VISIBLE);
            ll_top_container.setVisibility(View.INVISIBLE);
            call_time.setVisibility(View.VISIBLE);
            call_time.setBase(SystemClock.elapsedRealtime());
            call_time.start();
            thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    //在这里关闭不能重新连接
                    // closeConnectors();
                    cameraConnector = new CameraConnector();
                    cameraConnector.setOtherVideoPlayerSurfaceView(otherView);
                    cameraConnector.setVideoUniformScale(true,true);
                    cameraConnector.beginConnect(loginID);
                    microphoneConnector = new MicrophoneConnector();
                    microphoneConnector.beginConnect(loginID);

                }

            });
            thread2.start();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void closeConnectors() {
        try {
            call_time.stop();
            call_time.setVisibility(View.GONE);
            //MultimediaManagerFactory.GetSingleton().close();
            if (cameraConnector != null) {
                cameraConnector.disconnect();
            }
            if (microphoneConnector != null) {
                microphoneConnector.disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void cameraHasOpened() {
        //预览camera所用holder,不可为null或是隐藏，否则不能从摄像头获取数据
        SurfaceHolder holder = myView.getSurfaceHolder();
        MultimediaManagerFactory.GetSingleton().startCameraPreview(holder);
    }

    @Override
    public void cameraOpenFailed(Exception e) {
        e.printStackTrace();
    }

    public void onEventMainThread(CallEvent event) {
        if (event.isEcho) {
            terminate("已经在其它设备上做出了应答！");
        } else {
            if(!event.target.equals(userId)||event.mediaType!=CommunicateMediaType.Video)
            {return;}
            if (event.communicateType == CommunicateType.Agree) {
                agree(event);
            } else if (event.communicateType == CommunicateType.Reject) {
                terminate("对方拒绝您的视频邀请!");
            } else if (event.communicateType == CommunicateType.Terminate) {
                terminate("对方已挂断!");
            } else if (event.communicateType == CommunicateType.Busy) {
                terminate("对方忙线中!");
            }

        }
    }

    public void onEventMainThread(RequestEvent event) {
        if (event.mediaType == CommunicateMediaType.Offline) {
            clientType = event.clientType;
            if(clientType==null){
                terminate("已掉线，视频中断!");
                return;
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Video, CommunicateType.Terminate, "", clientType.ordinal());
                    terminate("视频已中断!");
                }
            });
        }
    }

    public void onEventMainThread(UserEvent event) {
        if (event.status == UserStatus.OffLine&&event.userID.equals(userId)) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    terminate("对方已下线!");
                }
            });
        }
    }

}

